package com.boge.core.controller;

import java.io.IOException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.boge.core.model.entity.User;
import com.boge.core.service.UserLockService;
import com.boge.core.service.UserService;
import com.boge.util.ParamUtil;
import com.boge.util.websocket.WebsocketEndPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.TextMessage;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;

@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {

	@Autowired
	WebsocketEndPoint websocketEndPoint;

	@Resource
	UserService userService;

	@Resource
	UserLockService userLockService;

	public LoginController() {
	}

	/**
	 * 进入登录页
	 * @return
	 */
	@RequestMapping()
	public String login(HttpServletRequest request){
		String error = request.getParameter("error");
		request.setAttribute("error", error);
		return "login";
	}

	@RequestMapping("/jumpLogin")
	public static String jumpLogin() {
		return "jumpLogin";
	}

	@RequestMapping("/qqLogin")
	public String login(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=utf-8");
        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
        } catch (QQConnectException e) {
            e.printStackTrace();

        }
        return "login/qqLogin";
	}

	/**
	 * 登录校验，进入首页
	 * @param userName
	 * @param password
	 * @param response
	 * @param request
	 */
	@RequestMapping("/conformLogin")
	public void findUserByUserName(String userName, String password, HttpServletResponse response, HttpServletRequest request){
		User user = userService.findUserByUserName(userName);

		String path = request.getContextPath();
		String bathPath = request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + path + "/";

		//判断用户是否被锁住
		int userLockCount = userLockService.getUserLockCountsByUserId(user.getUserId());
		if (userLockCount == 3) {
			try {
				String error = "连续三次登录失败，请第二天再次登录";
				//通过url传递参数，如果含有中文，需要转码
				error = URLEncoder.encode(error, "UTF-8");
				response.sendRedirect(bathPath + "login?error=" + error);
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (user != null && password.equals(user.getUserPassword())) {
			//登录成功
			try {
				//将用户信息存入静态资源
				ParamUtil.user = user;
				//清空用户锁
				userLockService.deleteUserLockByUserId(user.getUserId());
				request.getSession().setAttribute("userId", user.getUserId());
				//在线人数统计
				if (!WebsocketEndPoint.onlineUserMap.containsKey(user.getUserId())) {
					synchronized (this) {
//						WebsocketEndPoint.onlineNum ++;
						WebsocketEndPoint.onlineUserMap.put(user.getUserId(), user);
					}
				}

				response.sendRedirect(bathPath + "home");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				//登录失败，用户锁+1
				if (user != null) {
					userLockService.raiseUserLockCountByUserId(user.getUserId());
				}
				String error = "用户名或密码错误";
				//通过url传递参数，如果含有中文，需要转码
				error = URLEncoder.encode(error, "UTF-8");
				response.sendRedirect(bathPath + "login?error=" + error);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@RequestMapping("/afterQQLogin")
	public String qqLogin(HttpServletRequest request) {
		System.out.println("afterQQLogin...");
		String accessToken = null;
		String openId = null;
		try {
			AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
			System.out.println("getAccessToken:" + accessTokenObj.getAccessToken());
			if (accessTokenObj.getAccessToken().equals("")) {
				System.out.println("QQ登录-没有获取到响应参数");
			} else {
				accessToken = accessTokenObj.getAccessToken();
				//根据accessToken获取openId
				OpenID openIDObj = new OpenID(accessToken);
				openId = openIDObj.getUserOpenID();
			}
		} catch (QQConnectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (openId == null) {
			request.setAttribute("msg", "网络不稳定，请稍后再试");
			return "jumpLogin";
		} else {
			//与数据库对接
			System.out.println("openId:" + openId);
		}

		return "home";
	}

	//无用
	@RequestMapping("/message")
	public String sendMessage(HttpSession session) {
		System.out.println("@RequestMapping:" + session.getAttribute("userId"));
//		boolean flag = websocketEndPoint.sendMessageToUser((Integer) session.getAttribute("userId"), new TextMessage("发送消息"));
		boolean flag = websocketEndPoint.sendMessageToAllUsers(new TextMessage("发送消息"));
		System.out.println("flag:" + flag);
		return "login";
	}

}

	
	